package com.treasure.mall.biz.service.core.user.impl;

import com.treasure.mall.biz.base.AbstractCrudService;
import com.treasure.mall.biz.dto.BaseSaveDTO;
import com.treasure.mall.biz.dto.user.UserAddressSaveDTO;
import com.treasure.mall.biz.entity.user.UserAddressPO;
import com.treasure.mall.biz.repository.user.UserAddressRepository;
import com.treasure.mall.biz.service.core.user.UserAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author allan
 * @version 1.0.0
 * @date 2020/7/6
 */
@Service
public class UserAddressServiceImpl extends AbstractCrudService<UserAddressPO, Long> implements UserAddressService {
    private UserAddressRepository addressRepository;

    @Autowired
    protected UserAddressServiceImpl(UserAddressRepository repository) {
        super(repository);
        this.addressRepository = repository;
    }

    @Override
    public UserAddressPO findDefault(Long userId) {
        return addressRepository.findTopByUserIdOrderByDefAddrDesc(userId);
    }

    @Override
    public List<UserAddressPO> findByUser(Long userId) {
        return addressRepository.findByUserId(userId);
    }

    @Override
    public void setDefault(Long id, Long userId) {
        UserAddressPO userAddressPO = findById(id);
        userAddressPO.setDefAddr(true);
        //把之前的设置为非默认
        UserAddressPO defaultAddr = findDefault(userId);
        if (defaultAddr != null) {
            defaultAddr.setDefAddr(false);
            save(defaultAddr);
        }

        save(userAddressPO);
    }

    @Override
    @Transactional
    public UserAddressPO save(BaseSaveDTO saveDTO) {
        UserAddressSaveDTO addressSaveDTO = (UserAddressSaveDTO) saveDTO;
        UserAddressPO userAddressPO;
        if (addressSaveDTO.getId() > 0) {
            userAddressPO = findById(addressSaveDTO.getId());
        } else {
            userAddressPO = new UserAddressPO();
            userAddressPO.setUserId(addressSaveDTO.getUserId());
        }

        if (addressSaveDTO.isDefAddr()) {
            //把之前的设置为非默认
            UserAddressPO defaultAddr = findDefault(addressSaveDTO.getUserId());
            if (defaultAddr != null) {
                defaultAddr.setDefAddr(false);
                save(defaultAddr);
            }
        }
        userAddressPO.setReceivingInfo(addressSaveDTO.getReceivingInfo());
        userAddressPO.setDefAddr(addressSaveDTO.isDefAddr());
        return save(userAddressPO);
    }
}
